import fs from 'node:fs/promises'
import path from 'node:path'
import { fileURLToPath } from 'node:url'

const __filename = fileURLToPath(import.meta.url)
const __dirname = path.dirname(__filename)

/**
 * 复制当前项目模板到插件的 template 目录
 */
async function copyCurrentTemplate(): Promise<void> {
    const pluginDir = path.resolve(__dirname, '..')
    const templateDir = path.join(pluginDir, 'template')
    const sourceDir = path.resolve(pluginDir, '..')

    console.log('正在复制模板文件...')
    console.log(`源目录: ${sourceDir}`)
    console.log(`目标目录: ${templateDir}`)

    // 需要排除的文件和目录
    const excludePatterns = [
        'node_modules',
        'dist',
        '.git',
        'pnpm-lock.yaml',
        'package-lock.json',
        'yarn.lock',
        'hzy-uni-cli', // 排除插件目录本身
        '.DS_Store',
    ]

    try {
        // 确保目标目录存在
        await fs.mkdir(templateDir, { recursive: true })

        // 递归复制文件
        await copyDirectory(sourceDir, templateDir, excludePatterns)

        console.log('✅ 模板文件复制完成')
    } catch (error) {
        console.error('❌ 复制失败:', error)
        throw error
    }
}

/**
 * 递归复制目录
 * @param src 源目录
 * @param dest 目标目录
 * @param excludePatterns 排除的模式
 */
async function copyDirectory(
    src: string,
    dest: string,
    excludePatterns: string[]
): Promise<void> {
    const entries = await fs.readdir(src, { withFileTypes: true })

    for (const entry of entries) {
        const srcPath = path.join(src, entry.name)
        const destPath = path.join(dest, entry.name)

        // 检查是否应该排除
        if (excludePatterns.includes(entry.name)) {
            continue
        }

        if (entry.isDirectory()) {
            await fs.mkdir(destPath, { recursive: true })
            await copyDirectory(srcPath, destPath, excludePatterns)
        } else {
            await fs.copyFile(srcPath, destPath)
        }
    }
}

// 如果直接运行此文件
if (import.meta.url === `file://${process.argv[1]}`) {
    copyCurrentTemplate().catch(console.error)
}

export { copyCurrentTemplate }
